import { useState } from 'react';

import AInput from '../components/AInput';

const metas = [
    { name: 'Name', value: '' },
    { name: 'Choose an Option', value: '', type: 'selector', options: [ 'Windows', 'Mac', 'Linux' ] },
    { name: 'Interests', value: [], type: 'checkboxes', options: [ 'Sport', 'Music', 'Art' ] },
    { type: 'submit' },
];

export default function App() {
    const [ formData, setFormData ] = useState(metas
                                                   .filter(meta => meta?.name?.length)
                                                   .reduce((acc, meta) => {
                                                       acc[meta.name] = meta.value;
                                                       return acc;
                                                   }, {}));

    const handleChange = ({ name, value }) => {
        console.trace('handleChange will invoke ...', { name, value, formData });
        const newFormData = { ...formData };
        newFormData[name] = value;
        console.info('handleChange had invoked ...', newFormData);
        setFormData(newFormData);
    };

    const handleSubmit = e => {
        console.trace('handleSubmit.e', e);
        e.preventDefault();
        console.log('handleSubmit.formData', formData);
        alert(JSON.stringify(formData, null, 4));
    };

    const content = metas.map((meta, index) => <AInput key={index} handleChange={handleChange} {...meta}></AInput>);
    return (<form onSubmit={handleSubmit}>{content}</form>);
};